package mychat.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import mychat.util.MessageFactory;
import mychat.vo.Message;
import mychat.vo.User;

public class ClientProcessor extends Thread {

	private Socket s;
	private DataOutputStream out;
	private DataInputStream in;
	private boolean start = false;
	private User user;

	public ClientProcessor(Socket s, DataOutputStream out, DataInputStream in,
			User user) {
		this.s = s;
		this.out = out;
		this.in = in;
		this.user = user;
		start = true;
	}

	public void run() {
		System.out.println("A Client OK!");
		sendMessage(MessageFactory.getSysMessage(user.toString()));
		sendMessage(MessageFactory.getSysMessage(Server.processorList
				.toString()));
		try {
			while (start) {
				String str = in.readUTF();
				System.out.println(str);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			close();
			this.interrupt();
			System.out.println("A Client 离线！");
			//e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
			} finally {
				try {
					if (out != null)
						out.close();
				} catch (IOException e) {
				} finally {
					try {
						if (!s.isClosed())
							s.close();
					} catch (IOException e) {
					}
				}
			}

		}

	}

	public Socket getSocket() {
		return s;
	}

	public User getUser() {
		return user;
	}

	public String getUserName() {
		return user.getName();
	}

	public void sendMessage(Message msg) {
		try {
			if (start)
				out.writeUTF(msg.toString());
			else
				throw new IOException("对方已离线！");
		} catch (IOException e) {
			System.out.println("发送失败！");
			e.printStackTrace();
		}

	}

	public void close() {
		start = false;
	}

}
